import { defineStore } from 'pinia'
import * as loginMethods from '@/apis/login'
import * as commonMethods from '@/apis/common'

// 把token存在状态管理工具pinia中
export const useTokenInfoStore = defineStore('useTokenInfoStore', {
    state:() => {
        return {
            userId: null,
            accessToken : "",
            refreshToken: "",
            expiresTime: null
        }
    },
    getters: {
        getterUserId: (state) => state.userId,
        getterAccessToken: (state) => state.accessToken,
        getterRefreshToken: (state) => state.refreshToken,
        getterExpiresTime: (state) => state.expiresTime,
        getterState: (state) => state
    },
    actions:{
        // 发送请求之前检测token是否过期和是否满足更新条件，满足就直接更新
        beforeRquestCheckAndDoRefreshToken(refreshToken,expresTime){
            return this.doAndCheckRefreshToken(refreshToken,expresTime)
        },
        async doAndCheckRefreshToken(refreshToken,expresTime){
            if(loginMethods.validateCanGetRefreshToken(refreshToken,expresTime)){
            const res = await commonMethods.AsyncCheckResultThenReturnData(await loginMethods.getRefreshToken(refreshToken))
            console.log('看看res',res);
            if(res !== this.state){
                // 当更新成功，返回1
                console.log('更新token请求成功')
                this.$state = res
                loginMethods.saveTokenInfoInLocalStorage()
                return commonMethods.commonResult(0,res,'更新token请求成功')
            }else{
                // 当请求失败，返回2
                localStorage.removeItem("tokenInfo");
                router.push("/")
                return 2
            }
            }else {
                // 判断不满足更新条件则返回3
                return 3
            }
        },

        getTokenInfoStr(){
            return{
                userId: this.userId,
                accessToken : this.accessToken,
                refreshToken: this.refreshToken,
                expiresTime: this.expiresTime
            }
        },

        setTokenInfoStr(value){
            console.log("value",value);
            return {
                userId: value.userId,
                accessToken:  value.accessToken,
                refreshToken:  value.refreshToken,
                expiresTime:  value.expiresTime
            }
        }
    }
  })

// export const userInfo = defineStore('userInfo',{
//     state:() => ()
// })